<script setup>
import {
  getNoticeApi,
  deleteNoticeApi,
  addNoticeApi,
  changeNoticeApi,
  updateStatusApi
} from '@/api/level'
import { ref, onMounted } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import ListHeader from '@/components/list-header.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getNoticeApi(currentPage.value)
    tableData.value = res.list
    total.value = res.totalCount
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除公告
const onDelete = async (row) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteNoticeApi(row.id)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('删除失败', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
  console.log(row)
}

//新增公告
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增'
  fromDrawerRef.value.open()
  form.value = {
    name: '',
    level: 0,
    status: 1,
    discount: null,
    max_price: null,
    max_times: null
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  name: '',
  level: 0,
  status: 1,
  discount: null,
  max_price: null,
  max_times: null
})

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()
  if (changId.value !== 0) {
    try {
      await changeNoticeApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('当前是演示环境', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await addNoticeApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('当前是演示环境', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改公告
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改'
  const { id, name, level, status, discount, max_price, max_times } = row
  form.value = {
    name,
    level,
    status,
    discount,
    max_price,
    max_times
  }
  changId.value = id
  fromDrawerRef.value.open()
}

//修改状态
const onChangeStatus = async (status, row) => {
  row.statusLoading = true
  try {
    await updateStatusApi(row.id, status)
    toast('修改状态成功')
    row.status = status
  } catch (error) {
    toast('当前是演示环境', 'error')
  } finally {
    row.statusLoading = false
  }
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <ListHeader @create="onAdd" @refresh="getData"></ListHeader>
  </el-card>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="name" label="会员等级" />
    <el-table-column prop="discount" label="折扣率(%)" />
    <el-table-column prop="level" label="等级序号" />
    <el-table-column prop="content" label="状态" width="120">
      <template #default="{ row }">
        <el-switch
          v-model="row.status"
          :active-value="1"
          :inactive-value="0"
          @change="onChangeStatus($event, row)"
          :loading="row.statusLoading"
          :disabled="row.super == 1"
        >
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180" align="center" fixed="right">
      <template #default="scoped">
        <el-button type="primary" size="small" text @click="onChange(scoped.row)">修改</el-button>

        <el-popconfirm
          title="是否要删除该等级？"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="onDelete(scoped.row)"
        >
          <template #reference>
            <el-button type="primary" size="small" text>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex justify-center justify-center mt-5">
    <el-pagination
      @current-change="getData"
      :current-page="currentPage"
      background
      layout="prev,pager,next"
      :total="total"
    />
  </div>
  <FromDrawer ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
      <el-form-item label="等级名称" prop="name">
        <el-input v-model="form.name" placeholder="等级名称"></el-input>
      </el-form-item>
      <el-form-item label="等级权重" prop="level">
        <el-input type="number" v-model="form.level" placeholder="等级权重"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"> </el-switch>
      </el-form-item>
      <el-form-item label="升级条件">
        <div>
          <small class="text-xs mr-2">累计消费满</small>
          <el-input
            type="number"
            v-model="form.max_price"
            placeholder="累计消费"
            style="width: 50%"
          >
            <template #append>元</template>
          </el-input>
          <small class="text-gray-400 flex">
            设置会员等级所需要的累计消费必须大于等于0,单位：元
          </small>
        </div>
        <div>
          <small class="text-xs mr-2">累计次数满</small>
          <el-input
            type="number"
            v-model="form.max_times"
            placeholder="累计次数"
            style="width: 50%"
          >
            <template #append>%</template>
          </el-input>
          <small class="text-gray-400 flex">
            设置会员等级所需要的购买量必须大于等于0,单位：笔
          </small>
        </div>
      </el-form-item>
      <el-form-item label="折扣率(%)" prop="discount">
        <el-input type="number" v-model="form.discount" placeholder="折扣率(%)" style="width: 50%">
          <template #append>%</template>
        </el-input>
        <small class="text-gray-400 flex">
          折扣率单位为百分比，如输入90，表示该会员等级的用户可以以商品原价的90%购买
        </small>
      </el-form-item>
    </el-form>
  </FromDrawer>
</template>

<style scoped></style>
